import React, { useEffect, useState } from "react";
import { Table, Card, Button, Popconfirm, message } from "antd";
import { withRouter } from "react-router";

import { listApi, delOne } from "../../../services/products";

function List(props) {
  const columns = [
    {
      title: "序号",
      key: "id",
      width: 80,
      align: "center",
      render: (text, record, index) => index + 1,
    },
    {
      title: "名字",
      dataIndex: "name",
      align: "center",
    },
    {
      title: "价格",
      dataIndex: "price",
      align: "center",
    },
    {
      title: "操作",
      render: (text, record, index) => (
        <div>
          <Button
            type="primary"
            size="small"
            onClick={() =>
              props.history.push(`/admin/products/edit/${record.id}`)
            }
          >
            修改
          </Button>
          <Popconfirm
            title="确定删除此项?"
            onConfirm={() => {
              message.success("用户确认删除！");
              //todo:调用aip接口进行删除
              delOne(record.id).then((res) => {
                message.success(res.message);
                loadData();
              });
            }}
            onCancel={() => message.error("用户取消删除！")}
            okText="Yes"
            cancelText="No"
          >
            <Button type="danger" size="small" style={{ margin: "0 1rem" }}>
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    loadData();
  }, []);

  function loadData() {
    listApi().then((res) => {
      setDataSource(res.products);
    });
  }

  return (
    <div>
      <Card
        title="商品列表"
        extra={
          <Button
            type="primary"
            size="small"
            onClick={() => props.history.push("/admin/products/edit")}
          >
            新增
          </Button>
        }
      >
        <Table
          rowKey="id"
          columns={columns}
          dataSource={dataSource}
          bordered
        ></Table>
      </Card>
    </div>
  );
}

export default withRouter(List);
